<template>
  <VPage>
    <el-row
      :gutter="10"
      class="bg-[var(--base-bg-color)] overflow-hidden"
      v-loading="loading"
    >
      <el-col :span="12">
        <el-card class="mb-2" shadow="never">
          <template #header>
            <div class="card-header text-base flex justify-between items-center">
              <span>目标完成情况</span>
              <svg-icon
                class="text-[var(--base-text-color)]"
                icon-class="RefreshRight"
                @click="refresh('target_board')"
              ></svg-icon>
            </div>
          </template>
          <div class="progress">
            <template v-if="datum.target_board_list.length">
              <div
                class="progress-item"
                v-for="item in datum.target_board_list"
                :key="item.id"
              >
                <div class="font-bold">
                  [{{ item.goods_target_config.target_rule_text }}][{{
                    item.goods_target_config.dimensionality_text
                  }}]{{ item.goods_target_config.target_type_text }}
                </div>
                <div class="py-2 text-[var(--base-sub-text-color )]">
                  {{ item.goods_target_config.month_start }}-{{
                    item.goods_target_config.month_end
                  }}
                  (<span :class="`text-[${item.textColor}] font-bold mx-[2px]`">{{
                    item.goods_target_config.remaining_days
                  }}</span
                  >)
                </div>
                <div class="py-2">
                  <span class="text-lg font-bold">{{ item.finish_value }}</span> |
                  {{ item.target_value }}
                </div>
                <div class="pt-2">
                  <el-progress
                    :color="item.textColor"
                    :percentage="computePercentage(item)"
                  />
                </div>
              </div>
            </template>
            <div class="text-center text-[var(--base-placeholder-text-color)]" v-else>
              暂无配置目标
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col v-if="permission_gross_profit_margin" :span="6">
        <el-card class="mb-2" shadow="never" style="border-radius: 8px; border: none">
          <template #header>
            <div class="card-header text-base flex justify-between items-center">
              <span>新品产品毛利率</span>
              <svg-icon
                class="text-[var(--base-text-color)]"
                icon-class="RefreshRight"
                @click="refresh('percent_income_all')"
              ></svg-icon>
            </div>
          </template>

          <div
            class="base-text-color font-bold text-[50px] flex justify-center items-center h-[162px]"
          >
            {{ datum.percent || 0 }} %
          </div>
        </el-card>
      </el-col>
      <el-col v-if="permission_sales_volume" :span="6">
        <el-card class="mb-2" shadow="never" style="border-radius: 8px; border: none">
          <template #header>
            <div class="card-header text-base flex justify-between items-center">
              <span>新品总销售额</span>
              <svg-icon
                class="text-[var(--base-text-color)]"
                icon-class="RefreshRight"
                @click="refresh('percent_income_all')"
              ></svg-icon>
            </div>
          </template>

          <div
            class="base-text-color font-bold text-[36px] flex justify-center items-center h-[162px]"
          >
            {{ datum.income_all || 0 }} CNY
          </div>
        </el-card>
      </el-col>
      <el-col v-if="permission_through_rate" :span="12">
        <el-card shadow="never" style="border-radius: 8px; border: none">
          <template #header>
            <div class="card-header text-base flex justify-between">
              <span>推品通过率</span>
              <div class="flex items-center">
                <el-date-picker
                  v-model="form.month"
                  type="month"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择月份"
                  @change="getDevelopPercentData"
                />
                <svg-icon
                  class="text-[var(--base-text-color)] ml-2"
                  icon-class="RefreshRight"
                  @click="refresh('develop_percent')"
                ></svg-icon>
              </div>
            </div>
          </template>
          <barEcharts :options="datum.develop_percent"></barEcharts>
        </el-card>
      </el-col>
      <el-col v-if="permission_stocking_rate" :span="12">
        <el-card shadow="never" style="border-radius: 8px; border: none">
          <template #header>
            <div class="card-header text-base flex justify-between">
              <span>新品二次备货率</span>
              <svg-icon
                class="text-[var(--base-text-color)]"
                icon-class="RefreshRight"
                @click="refresh('prepareStock_percent')"
              ></svg-icon>
            </div>
          </template>
          <barEcharts :options="datum.prepareStock_percent"></barEcharts>
        </el-card>
      </el-col>
    </el-row>
  </VPage>
  <noticeModal ref="noticeRef"></noticeModal>
  <warehouseVolume ref="warehouseVolumeRef"></warehouseVolume>
</template>
<script name="BoardIndex" setup>
import { ref, reactive, toRefs, onMounted } from "vue";
import {
  getDataboardExpense,
  getPrepareStockPercent,
  getDevelopPercent,
  getTargetBoard,
} from "./api/index.js";
import barEcharts from "@/components/Echarts/barEcharts";

const data = reactive({
  datum: {
    target_board_list: [],
  },
  loading: false,
  form: {},
});
const { datum, loading, form } = toRefs(data);

const getDataboardExpenseData = async () => {
  try {
    const res = await getDataboardExpense();
    datum.value.income_all = res.data.income_all;
    datum.value.percent = res.data.percent;
  } catch (e) {
    throw Error(e);
  }
};

const getPrepareStockPercentData = async () => {
  try {
    const res = await getPrepareStockPercent();
    const prepareStock_percent = {
      title: "",
      yAxisName: "单位：%",
      seriesName: "新品二次备货率",
      yAxisData: [],
      xAxisData: [],
      axisLabel: { interval: 0, rotate: 30 },
    };
    if (res.data?.length) {
      res.data.forEach((item) => {
        prepareStock_percent.yAxisData.push(item.percent);
        prepareStock_percent.xAxisData.push(item.user_name);
      });
    }
    datum.value.prepareStock_percent = prepareStock_percent;
  } catch (e) {
    throw Error(e);
  }
};

const getDevelopPercentData = async () => {
  try {
    const res = await getDevelopPercent({
      month: form.value.month,
    });
    const develop_percent = {
      title: "",
      yAxisName: "单位：%",
      seriesName: "推品通过率",
      yAxisData: [],
      xAxisData: [],
      axisLabel: { interval: 0, rotate: 30 },
    };
    if (res.data?.length) {
      res.data.forEach((item) => {
        develop_percent.yAxisData.push(item.percent);
        develop_percent.xAxisData.push(item.user_name);
      });
    }
    datum.value.develop_percent = develop_percent;
  } catch (e) {
    throw Error(e);
  }
};

const getTargetBoardList = async () => {
  try {
    const res = await getTargetBoard();
    datum.value.target_board_list = res.data.map((item) => {
      item.goods_target_config.remaining_days = computedDay(
        item.goods_target_config.month_end
      );
      item.textColor = computedColor(item);
      return item;
    });
  } catch (e) {
    throw Error(e);
  }
};

// 计算当前距离结束时间剩余天数
const computedDay = (month_end) => {
  const currentDate = new Date();
  const endDate = new Date(month_end);
  endDate.setHours(23, 59, 59, 999);
  const timeDifference = endDate - currentDate;
  const dayDifference = Math.ceil(timeDifference / (1000 * 60 * 60 * 24));
  return dayDifference >= 0 ? dayDifference : 0;
};

// 计算颜色
const computedColor = (item) => {
  if (item.target_value === item.finish_value) {
    return "#67C23A";
  } else {
    if (item.goods_target_config.remaining_days <= 7) {
      return "#E50113";
    } else if (item.goods_target_config.remaining_days > 7) {
      return "#3487FF";
    }
  }
};

const computePercentage = (item) => {
  return ((item.finish_value / item.target_value) * 100).toFixed(2);
};

// 新品毛利率权限
const permission_gross_profit_margin = computed(() => {
  return (window.BTN_AUTH || []).includes("/goods/board/gross-profit-margin");
});

// 新品销售额
const permission_sales_volume = computed(() => {
  return (window.BTN_AUTH || []).includes("/goods/board/sales-volume");
});

// 推品通过率
const permission_through_rate = computed(() => {
  return (window.BTN_AUTH || []).includes("/goods/board/through-rate");
});

// 新品二次备货率
const permission_stocking_rate = computed(() => {
  return (window.BTN_AUTH || []).includes("/goods/board/stocking-rate");
});

const fetchData = async () => {
  try {
    await Promise.all([
      getDataboardExpenseData(),
      getPrepareStockPercentData(),
      getDevelopPercentData(),
      getTargetBoardList(),
    ]);
  } catch (error) {
    loading.value = false;
    console.error("Error fetching data:", error);
  }
};

const refresh = (type) => {
  loading.value = true;

  switch (type) {
    case "target_board":
      getTargetBoardList();
      break;
    case "percent_income_all":
      getDataboardExpenseData();
      break;
    case "develop_percent":
      getDevelopPercentData();
      break;
    case "prepareStock_percent":
      getPrepareStockPercentData();
      break;
    default:
      break;
  }
  setTimeout(() => {
    loading.value = false;
  }, 500);
};

onMounted(async () => {
  loading.value = true;
  await fetchData();
  loading.value = false;
});
</script>
<style lang="scss">
.v-page__body {
  background: var(--base-bg-color) !important;
}
</style>
<style lang="scss" scoped>
.progress {
  min-height: 160px;
  overflow-x: auto;
  display: flex;
  flex-wrap: nowrap;
  white-space: nowrap;
  padding-bottom: 6px;
}
.progress-item {
  background: linear-gradient(
    to bottom,
    var(--base-primary-bg) 0%,
    var(--base-color) 100%
  );
  border: 1px solid var(--base-border-color);
  padding: 12px;
  margin-right: 12px;
  border-radius: 5px;
  width: 300px;
}
</style>
